<?php

class EditionManager extends Manager
{
	const TABLE_NAME = 'wydania';
	const TABLE_AVAIL_NAME = 'dostepne_egzemplarze';
	const OBJECT_NAME = 'Edition';
	const PK_NAME = 'isbn';

	public function getByIsbn($isbn)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME)
					->join(self::TABLE_AVAIL_NAME, 
						self::TABLE_AVAIL_NAME . '.isbn = ' . self::TABLE_NAME . '.isbn', 'SUM(' . self::TABLE_AVAIL_NAME . '.dostepny) as dostepne')
					->where(self::TABLE_NAME . '.isbn = ?', $isbn);
		return $this->_fetchObject(self::OBJECT_NAME, $select);
	}

	public function getByBookId($id)
	{
		$select = $this->_db->select()->from(self::TABLE_NAME, self::TABLE_NAME . '.*')
					->join(self::TABLE_AVAIL_NAME, 
						self::TABLE_AVAIL_NAME . '.isbn = ' . self::TABLE_NAME . '.isbn', 'SUM(' . self::TABLE_AVAIL_NAME . '.dostepny) as dostepne')
					->where('idKsiazki = ?', $id)
					->group(self::TABLE_NAME . '.isbn');
		return $this->_fetchCollection(self::OBJECT_NAME, $select);
	}
	
	public function search($title, $author)
	{
		$title = "%$title%";
		$select = $this->_db->select()->from(self::TABLE_NAME, self::TABLE_NAME . '.*')
					->join(AuthorManager::TABLE_NAME, 
						AuthorManager::TABLE_NAME . '.id = ' . self::TABLE_NAME . '.glownyAutor', array(AuthorManager::TABLE_NAME . '.imie', AuthorManager::TABLE_NAME . '.nazwisko'))
					->where('tytul LIKE ?', $title);
		if ($author) {
			$author = "%$author%";
			$select->where('nazwisko LIKE ? OR imie LIKE ?', $author);
		}
					
		$select->join(self::TABLE_AVAIL_NAME, 
						self::TABLE_AVAIL_NAME . '.isbn = ' . self::TABLE_NAME . '.isbn', 'SUM(' . self::TABLE_AVAIL_NAME . '.dostepny) as dostepne')
				->group(self::TABLE_NAME . '.isbn');
					
		return $this->_fetchCollection(self::OBJECT_NAME, $select);
	}
	
}